<template>
  <!-- 西/成药处方 -->
  <section id="xiyaoEl">
    <el-form :model="form" ref="form">
      <table class="table-box">
        <thead>
          <tr>
            <th>组号</th>
            <th>单次剂量</th>
            <th>用法</th>
            <th>用药频次</th>
            <th>天数</th>
            <th>总量</th>
            <th>取药</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in form.tableList" :key="index">
            <td>
              <div class="drug-title">
                <el-tooltip
                  effect="dark"
                  :content="'￥：' + item.medicalDrugSale.sellMoney"
                  placement="right"
                >
                  <el-link
                    :underline="false"
                    type="primary"
                    class="vertical-middle"
                  >{{ item.drugName }}</el-link>
                </el-tooltip>&nbsp;&nbsp;&nbsp;
                <span class="vertical-middle">
                  规格：{{ item.specs }}，库存：{{
                  item.inventory | durgInventory(oneDoseUnitArr, "showZero")
                  }}
                </span>
                <span :class="item.highWarning==1?'hight':''">{{item.highWarning==1?'(高危药品！)':''}}</span>
                <span class="antibacterial">{{item.antibacterial==1?'(抗菌药物)':'(非抗菌药物)'}}</span>
              </div>
              <el-form-item :prop="'tableList.' + index + '.groupId'" :rules="[rulesRequired]">
                <el-select :disabled="toDisabled(item)" v-model="item.groupId">
                  <el-option v-for="(item, index) in 10" :key="index" :value="item" :label="item"></el-option>
                </el-select>
              </el-form-item>
            </td>
            <td>
              <el-form-item
                :prop="'tableList.' + index + '.oneDose'"
                :rules="[rulesRequired, integerAndFloat]"
              >
                <el-input v-model.number="item.oneDose" :disabled="toDisabled(item)" type="number">
                  <!-- <el-select v-model="item.oneDoseUnit" style="width:70px;" slot="append" placeholder="请选择">
                    <el-option v-for="(item,index) in oneDoseUnitArr" :key="index" :label="item.desc" :value="item.id"></el-option>
                  </el-select>-->
                  <span slot="append">{{ item.oneDoseUnit | changeAssist(oneDoseUnitArr) }}</span>
                </el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item :prop="'tableList.' + index + '.use'" :rules="rulesRequired">
                <el-select v-model="item.use" :disabled="toDisabled(item)" placeholder="请选择">
                  <el-option
                    v-for="(item, index) in useArr"
                    :key="index"
                    :label="item.desc"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </td>
            <td>
              <el-form-item :prop="'tableList.' + index + '.frequency'" :rules="rulesRequired">
                <el-select v-model="item.frequency" :disabled="toDisabled(item)" placeholder="请选择">
                  <el-option
                    v-for="(item, index) in frequencyArr"
                    :key="index"
                    :label="item.desc"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </td>
            <td>
              <el-form-item
                :prop="'tableList.' + index + '.useDay'"
                :rules="[rulesRequired, rulesNumber]"
              >
                <el-input v-model.number="item.useDay" :disabled="toDisabled(item)" type="number"></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item
                :prop="'tableList.' + index"
                :key="'tabkleList'+index"
                :rules="toDisabled(item)?null:ruleUseTotal"
              >
                <el-input v-model="item.useTotal" :disabled="toDisabled(item)">
                  <el-select
                    v-model="item.totalUnit"
                    slot="append"
                    style="width:70px;"
                    placeholder="请选择"
                    :disabled="toDisabled(item)"
                  >
                    <template v-for="(item2, index2) in oneDoseUnitArr">
                      <el-option
                        :key="index2"
                        v-if="showUnit(item2.id, item)"
                        :label="item2.desc"
                        :value="item2.id"
                      ></el-option>
                    </template>
                  </el-select>
                  <!-- <span slot="append">{{item.oneDoseUnit|changeAssist(oneDoseUnitArr)}}</span> -->
                </el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item :prop="'tableList.' + index + '.getAddress'" :rules="rulesRequired">
                <el-select v-model="item.getAddress" :disabled="toDisabled(item)" placeholder="请选择">
                  <el-option
                    v-for="(item, index) in getAddressArr"
                    :key="index"
                    :label="item.desc"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </td>
            <td>
              <div style="line-height:36px;width:80px;">
                <el-tooltip
                  :disabled="!item.remark"
                  effect="dark"
                  :content="item.remark"
                  placement="right"
                >
                  <el-link
                    v-if="!toDisabled(item)"
                    :underline="false"
                    @click="onOpenExplain(item)"
                    type="primary"
                  >
                    <i class="el-icon-edit"></i>说明
                  </el-link>
                </el-tooltip>&nbsp;&nbsp;&nbsp;
                <el-link
                  v-if="!toDisabled(item)"
                  :underline="false"
                  type="primary"
                  @click="onDelItem(item, index)"
                >
                  <i class="el-icon-delete"></i>
                </el-link>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </el-form>
    <br />
    <div>
      <dialogSearchDrug
        :patientId="patientId"
        :doctorId="doctorId"
        :channel="'MZCF'"
        @addItem="addFormList"
      ></dialogSearchDrug>
    </div>
    <br />
    <div class="form-tool">
      <div>
        <el-button @click="onSubmit" :loading="btnLoading" type="primary">保存</el-button>
      </div>
      <div>
        <!-- <el-button @click="dialogSaveCFtemplate=true">
          <i class="iconfont iconcunchu vertical-middle"></i>
          <span class="vertical-middle">存为模板</span>
        </el-button>-->
        <el-button v-if="form.tableList.length > 0 && templateSave.t1 == false" @click="onPrint">
          <i class="iconfont icondayin vertical-middle" style="font-size:20px;"></i>
          <span class="vertical-middle">打印处方</span>
        </el-button>
      </div>
    </div>
    <!-- 设置说明 -->
    <dialogCFExplain v-model="dialogExplain" :curItem="curItem"></dialogCFExplain>
    <!-- <dialogSaveCFtemplate v-model="dialogSaveCFtemplate" :list="form.tableList" :deptId="deptId" :doctorId="doctorId" :patientId="patientId"></dialogSaveCFtemplate> -->
    <dialogWestwardPrint v-model="dialogWestwardPrint" :cureId="cureId"></dialogWestwardPrint>
  </section>
</template>
<script>
import xyMixin from "../_js/xyMixin.js";
import Validate from "@/_js/validate.js";
export default {
  name: "prescriptionCr",
  mixins: [xyMixin],
  props: [
    "dataTemplateXY",
    "selectDrugArr",
    "cureId",
    "deptId",
    "doctorId",
    "patientId",
    "initData",
    "guoMinArr",
    "isCopy",
  ],
  components: {
    dialogSearchDrug: () => import("./dialogSearchDrug.vue"),
    // dialogSaveCFtemplate: () => import("./dialogSaveCFtemplate.vue"),
    dialogCFExplain: () => import("./dialogCFExplain.vue"),
    dialogWestwardPrint: () => import("@/pages/_com/dialogWestwardPrint.vue"),
  },
  computed: {},
  data() {
    let th = this;
    var ruleUseTotal = (rule, obj, callback) => {
      let reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
      console.log(obj);
      if (obj.useTotal !== "" && typeof obj.useTotal != "undefined") {
        if (reg.test(obj.useTotal)) {
          if (obj.totalUnit == obj.inventory.packUnit) {
            obj.useTotal > obj.inventory.packNum
              ? callback("使用数量大于库存数量")
              : callback();
          } else if (obj.totalUnit == obj.inventory.subsectionUnmUnit) {
            obj.useTotal > obj.inventory.usableNum
              ? callback("使用数量大于库存数量")
              : callback();
          } else {
            callback();
          }
        } else {
          callback(new Error("请输入整数或小数"));
        }
      } else {
        callback();
      }
    };
    return {
      deptName: "",
      doctorName: "",
      professionalDeptName: "",
      dialogWestwardPrint: false,
      isOpenEdit: false, //开启数据修改监听
      dialogSaveCFtemplate: false,
      hpId: "",
      btnLoading: false,
      curItem: null,
      dialogExplain: false,
      form: {
        tableList: [],
        curePrescription: {
          id: "", //======================================
          cureId: th.cureId,
          hpId: "",
          patientId: th.patientId,
          deptId: th.deptId,
          doctorId: th.doctorId,
        },
      },
      rulesRequired: {
        required: true,
        message: "此项必填",
        trigger: ["blur", "change"],
      },
      integerAndFloat: {
        validator: Validate.integerAndFloat,
        trigger: ["blur", "change"],
      },
      rulesNumber: {
        validator: Validate.integerNum,
        trigger: ["blur", "change"],
      },
      ruleUseTotal: {
        validator: ruleUseTotal,
        trigger: ["blur", "change"],
      },
    };
  },
  created() {
    let th = this;
    th.hpId = th.adminUser.hpId;
    th.form.curePrescription.hpId = th.hpId;
  },
  mounted() {
    let th = this;
    th.deptName = th.$route.query.deptName;
    th.doctorName = th.$route.query.doctorName;
    th.professionalDeptName = th.$route.query.professionalDeptName;
  },
  methods: {
    //打印
    onPrint() {
      let th = this;
      th.dialogWestwardPrint = true;
    },
    //提交处方()
    onSubmit() {
      let th = this;
      console.log(th.form);
      if (!th.form.curePrescription.id && th.form.tableList.length == 0) {
        return;
      }
      let j = {};
      let update = () => {
        th.btnLoading = true;
        th.$api
          .updatewesternMedicine(j)
          .then((res) => {
            if (res.executed) {
              th.$message.success("操作成功");
              th.$emit("submit");
              for (let i = 0; i < res.data.length; i++) {
                let d = res.data[i];
                for (let g = 0; g < th.form.tableList.length; g++) {
                  let el = th.form.tableList[g];
                  if (!el.id) {
                    el.id = d;
                    break;
                  }
                }
              }
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
            th.$nextTick(function () {
              th.isOpenEdit = true;
              th.$emit("submit");
            });
          })
          .catch(() => {
            th.btnLoading = false;
            th.isOpenEdit = true;
          });
      };
      let add = () => {
        th.btnLoading = true;
        th.$api
          .addMultiplewesternMedicine(j)
          .then((res) => {
            if (res.executed) {
              th.$message.success("操作成功");

              for (let i = 0; i < res.data.length; i++) {
                let d = res.data[i];
                if (i == 0) continue;
                else if (i == 1) {
                  // 处方id
                  th.form.curePrescription.id = d;
                } else {
                  //子项目id
                  th.form.tableList[i - 2].id = d;
                }
              }
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
            th.$nextTick(function () {
              th.isOpenEdit = true;
              th.$emit("submit");
            });
          })
          .catch(() => {
            th.btnLoading = false;
            th.isOpenEdit = true;
          });
      };
      th.$refs["form"].validate((v) => {
        if (v) {
          let cureArr = [];
          //循环剔除不要的数据
          th.form.tableList.forEach((d) => {
            let json = {};
            Object.assign(json, d);
            //计算价格
            json.sellMoney = json.medicalDrugSale.sellMoney;
            //判断是否拆分
            if (
              d.medicalDrugSale.isPiece == 1 &&
              json.totalUnit == d.medicalDrugSale.preparationUnit
            ) {
              json.sellMoney = d.medicalDrugSale.pieceMoney;
            }
            delete json.medicalDrugSale;
            delete json.inventory;
            delete json.isPiece;
            delete json.payStatus;
            delete json.status;
            cureArr.push(json);
          });
          j.curePrescription = JSON.stringify(th.form.curePrescription);
          j.curePrescriptionDrug = JSON.stringify(cureArr);
          //判断组
          if (th.judgeGroup()) {
            th.isOpenEdit = false;
            if (th.form.curePrescription.id) update();
            else add();
          } else {
            th.$message.warning("同组号的药品必须用法、频次、天数保持一致");
          }
        }
      });
    },
    //删除项
    onDelItem(obj, index) {
      let th = this;
      if (obj.id) {
        let j = {
          prescriptionDrugId: obj.id,
        };
        th.$api.prescriptionDrugpreDelete(j).then((res) => {
          if (res.executed && res.data) {
            th.form.tableList.splice(index, 1);
          } else {
            th.$message.warning(res.message);
          }
        });
      } else {
        th.form.tableList.splice(index, 1);
      }
    },
    //判断是否可编辑
    toDisabled(obj) {
      if (obj.payStatus == 2 && obj.status == 0) {
        return false;
      } else {
        return true;
      }
    },
  },
  watch: {
    dataTemplateXY(n) {
      let th = this;
      n.forEach((d) => {
        th.addFormList(d);
      });
    },
    selectDrugArr(n) {
      let th = this;
      if (n.length > 0) {
        n.forEach((item) => {
          item.groupId = item.groupId
            ? item.groupId
            : th.form.tableList.length + 1;
          th.addFormList(item);
        });
      }
    },
    "form.tableList": {
      deep: true,
      handler: function (n) {
        let th = this;
        if (!th.isOpenEdit) return;
        th.calculateTotal();
        if (!th.form.curePrescription.id && n.length == 0) {
          th.$emit("submit");
        } else {
          th.$emit("change");
        }
      },
    },
    initData: {
      deep: true,
      // immediate: true,
      handler: function (n) {
        let th = this;
        let fn = function () {
          if (n && n.curePrescriptionDrugInfos.length > 0) {
            th.form.tableList = n.curePrescriptionDrugInfos;
          }
          if (n && n.prescriptionId) {
            th.form.curePrescription.id = n.prescriptionId;
          }
          th.$nextTick(function () {
            th.isOpenEdit = true;
          });
        };
        let time = setInterval(function () {
          if (th.getAddressArr.length > 0) {
            clearInterval(time);
            fn();
          }
        }, 300);
      },
    },
    // begin -tl 修改
    isCopy:{
      deep:true,
      handler:function(n){
        this.form.curePrescription.id ='';
      }
    }
    // end
  },
};
</script>
<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 0;
}
.table-box {
  td {
    height: 80px;
    vertical-align: bottom;
    position: relative;
    .drug-title {
      position: absolute;
      top: 5px;
      left: 10px;
      min-width:800px;
      overflow: hidden;
    }
  }
}
.hight {
  color: #e6a23c;
  margin-left: 10px;
}
.antibacterial {
  margin-left: 10px;
  color: #409eff;
}
</style>
